//
//  ZMSearchListVC.swift
//  LeGou
//
//  Created by 刘亿前 on 2022/9/9.
//

import UIKit

class ZMSearchListVC: ZMViewController {
    // 搜索记录
    @IBOutlet weak var historyTop: NSLayoutConstraint!
    @IBOutlet weak var historyView: UIView!
    @IBOutlet weak var historyList: UICollectionView!
    // 清空记录
    @IBOutlet weak var clearBtn: UIButton!
    // 搜索结果
    @IBOutlet weak var resultList: UICollectionView!
    
    lazy var couponBtn: UIButton = {
        let btn = UIButton()
        btn.cornerRadius = 16
        btn.masksToBounds = true
        btn.layer.borderWidth = 1
        btn.layer.borderColor = "#DE3F26".zm.hex().cgColor
        btn.setTitle("只看有券商品", for: .normal)
        btn.setTitle("所有商品", for: .selected)
        btn.setTitleColor("#DE3F26".zm.hex(), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        return btn
    }()
    
    var type = ""
    var searchKey = ""
    var page = 1
    var pageSize = 10
    // 搜索记录
    var historyArr = [String]()
    // 搜索结果
    var resultArr = [Any]()
    var homeSearch = true
    var historyClick: ((_ str: String)->())?

    override func viewDidLoad() {
        super.viewDidLoad()
        glt_scrollView = resultList
        resultList.isHidden = true
        historyView.isHidden = false
        view.backgroundColor = "#F5F5F5".zm.hex()
        historyTop.constant = homeSearch ? 44 : 0
        setCollection()
        getHistory()
        bindAction()
    }
    
    func setCollection() {
        let layout = UICollectionViewLeftAlignedLayout()
        layout.minimumLineSpacing = 8
        layout.minimumInteritemSpacing = 8
        layout.scrollDirection = .vertical
        historyList.delegate = self
        historyList.dataSource = self
        historyList.setCollectionViewLayout(layout, animated: true)
        historyList.register(ZMSearchHistoryCell.self, forCellWithReuseIdentifier: "ZMSearchHistoryCell")
        
        let resultLayout = UICollectionViewFlowLayout()
        resultLayout.minimumLineSpacing = 8
        resultLayout.minimumInteritemSpacing = 8
        resultLayout.scrollDirection = .vertical
        resultLayout.headerReferenceSize = CGSize(width: SCREEN_W, height: 44)
//        resultLayout.sectionHeadersPinToVisibleBounds = true
        resultList.delegate = self
        resultList.dataSource = self
        resultList.setCollectionViewLayout(resultLayout, animated: true)
        resultList.register(UINib(nibName: "HomeGoodsCell", bundle: nil), forCellWithReuseIdentifier: "HomeGoodsCell")
        resultList.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "head")
        addRefresh(scrollView: resultList) { [unowned self] refresh in
            self.page = refresh ? 1 : self.page + 1
            self.requestList()
        }
        resultList.mj_footer?.isHidden = true
        resultList.mj_header?.isHidden = true
    }
    
    func getHistory() {
        if let arr = UserDefaults.standard.object(forKey: "\(type)_SearchHistory") as? [String] {
            historyArr = arr
            historyList.reloadData()
        }
        clearBtn.isHidden = historyArr.count == 0
    }
    
    func saveHistory() {
        if historyArr.contains(searchKey) {
           return
        }
        if historyArr.count == 10 {
            historyArr.removeLast()
        }
        historyArr.insert(searchKey, at: 0)
        UserDefaults.standard.set(historyArr, forKey: "\(type)_SearchHistory")
        UserDefaults.standard.synchronize()
        historyList.reloadData()
        clearBtn.isHidden = historyArr.count == 0
    }
    
    func bindAction() {
        clearBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            let config = AlertConfig("提示", "是否清空历史搜索记录")
            config.cancelBtnText = "否"
            config.sureBtnText = "是"
            ZMAlertView.alert(config: config) { [unowned self] (index) in
                if index >= 0 {
                    self.clearBtn.isHidden = true
                    UserDefaults.standard.set(nil, forKey: "\(type)_SearchHistory")
                    self.historyArr.removeAll()
                    self.historyList.reloadData()
                }
            }
        }).disposed(by: disposeBag)
        
        couponBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.couponBtn.isSelected = !self.couponBtn.isSelected
            self.resultList.mj_header?.beginRefreshing()
        }).disposed(by: disposeBag)
    }
    
    func giveSize(titleStr : String) -> CGSize {
        let imageStr = getAtrStr(titleStr: titleStr)
        let width = (SCREEN_W - 24 - 7 ) / 2 - 24
        imageStr.addAttributes([.font : UIFont.systemFont(ofSize: 14, weight: .medium)], range: NSRange(location: 0, length: imageStr.length))
        var size = imageStr.boundingRect(with: CGSize(width: width, height: 45), options: .usesLineFragmentOrigin, context: nil).size
        if size.height > 45 {
            size.height = 45
        }
        return size
    }
    
    func getAtrStr(titleStr : String) -> NSMutableAttributedString {
        let att = NSTextAttachment.init(data: nil, ofType: nil)
        att.image = UIImage.init(named: (type == "tb" ? "home_bg_icon" : type == "jd" ? "home_bg_icon" : "home_pdd"))
        att.bounds = CGRect(x: 0, y: -4, width: 20, height: 20)
        let imageStr = NSMutableAttributedString(attachment: att)
        imageStr.append(NSMutableAttributedString.init(string: titleStr))
        return imageStr
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        historyList.reloadData()
        resultList.reloadData()
    }
}

extension ZMSearchListVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == historyList {
            return historyArr.count
        }
        return resultArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == historyList {
            return CGSize(width: historyArr[indexPath.row].zm.size(font: UIFont.systemFont(ofSize: 14, weight: .regular)).width + 24, height: 32)
        } else {
            let width : CGFloat = (SCREEN_W - 24 - 7) / 2
            var title = ""
            if let d = resultArr[indexPath.row] as? TBGoods {
                title = d.title
            } else if let d = resultArr[indexPath.row] as? JDGoodsModel {
                title = d.skuName
            } else if let d = resultArr[indexPath.row] as? PDDModel {
                title = d.goodsName
            }
            let size = giveSize(titleStr: title)
            return CGSize(width: width, height: width + 15 + size.height + HomeGoodsCell.bootomH)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if collectionView == resultList {
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "head", for: indexPath)
            view.backgroundColor = .white
            view.addSubview(couponBtn)
            couponBtn.snp.makeConstraints { make in
                make.left.equalTo(16)
                make.right.equalTo(-16)
                make.height.equalTo(32)
                make.centerY.equalToSuperview()
            }
            return view
        } else {
            return UICollectionReusableView()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == historyList {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ZMSearchHistoryCell", for: indexPath) as! ZMSearchHistoryCell
            cell.name.text = historyArr[indexPath.row]
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeGoodsCell", for: indexPath) as! HomeGoodsCell
            if let data = resultArr[indexPath.row] as? TBGoods {
                cell.label.attributedText = getAtrStr(titleStr: data.title)
                cell.coupon.text = data.couponPrice.zm.toString(keep: 2) + "元"
                let handel = ZMUtil.DecimalNumberHandler(roundingMode: .down, scale: 2)
                let commissionMoney = NSDecimalNumber.init(value: data.commissionRate).dividing(by: NSDecimalNumber.init(value: 100)).multiplying(by: NSDecimalNumber.init(value: data.actualPrice)).rounding(accordingToBehavior: handel)
                cell.img.zm.setImage(urlStr: data.mainPic)
                cell.refund.text = "\(data.userCommission)元"
                cell.price.attributedText = "".zm.append(str: "¥", attri: ["f" : "12b", "c" : "#DC1826"])
                    .zm.append(str: "\(data.actualPrice.zm.toString(keep: 2))", attri: ["f" : "18b", "c" : "#DC1826"])
                    .zm.append(str: "券后", attri: ["f" : "12m", "c" : "#DC1826"])
                cell.subPrice.zm.setStrikethroughTitle(title: "¥\(data.originalPrice.zm.toString(keep: 2))")
            } else if let data = resultArr[indexPath.row] as? JDGoodsModel {
                cell.label.attributedText = getAtrStr(titleStr: data.skuName)
                if let url = data.imageInfo?.imageList[0].url {
                    cell.img.zm.setImage(urlStr: url)
                }
                if let info = data.couponInfo?.couponList[0] {
                    cell.coupon.text = info.discount.zm.toString(keep: 2) + "元"
                }
                cell.refund.text = "\(data.couponCommission.zm.toString())元"
                cell.price.attributedText = "".zm.append(str: "¥", attri: ["f" : "12b", "c" : "#DC1826"])
                    .zm.append(str: "\(data.lowestCouponPrice.zm.toString(keep: 2))", attri: ["f" : "18b", "c" : "#DC1826"])
                    .zm.append(str: "券后", attri: ["f" : "12m", "c" : "#DC1826"])
                cell.subPrice.zm.setStrikethroughTitle(title: "¥\(data.lowestPrice.zm.toString(keep: 2))")
            } else if let data = resultArr[indexPath.row] as? PDDModel {
                cell.pddUI(data)
            }
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == historyList {
            searchKey = historyArr[indexPath.row]
            requestList()
            if let block = historyClick {
                block(searchKey)
            }
        } else {
            if let info = resultArr[indexPath.row] as? TBGoods {
                let vc = TbDetailVC()
                vc.id = "\(info.goodsId)"
                navigationController?.pushViewController(vc, animated: true)
            } else if let info = resultArr[indexPath.row] as? JDGoodsModel {
                let vc = JDDetailVC()
                vc.id = info.skuId
                navigationController?.pushViewController(vc, animated: true)
            } else if let info = resultArr[indexPath.row] as? PDDModel {
                let vc = PddDetailVC()
                vc.goodsSign = info.goodsSign
                navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
}

// MARK: - Request Action
extension ZMSearchListVC {
    func requestList() {
        saveHistory()
        let pa = ["keyWords":searchKey,"limit":pageSize, "page":page, "coupon":(couponBtn.isSelected ? "1" : "0")] as [String : Any]
        if type == "tb" {
            let api = HomeAPI.tb_search(pa)
            ZMUtil.listRequest(type: TBGoods.self, api: api) { resp in
                self.relodaData(resp.data ?? [])
            }
        } else if type == "jd" {
            let api = HomeAPI.jd_search(pa)
            ZMUtil.listRequest(type: JDGoodsModel.self, api: api) { resp in
                self.relodaData(resp.data ?? [])
            }
        } else if type == "pdd" {
            let api = HomeAPI.pdd_search(pa)
            ZMUtil.listRequest(type: PDDModel.self, api: api) { resp in
                self.relodaData(resp.data ?? [])
            }
        }
    }
    func relodaData(_ data: [Any] = []) {
        historyView.isHidden = true
        resultList.isHidden = false
        addNodataScrollView(scrollView: resultList)
        resultList.mj_header?.endRefreshing()
        resultList.mj_footer?.endRefreshing()
        if page == 1 {
            resultArr.removeAll()
        }
        resultArr.append(contentsOf: data)
        if data.count < pageSize {
            resultList.mj_footer?.endRefreshingWithNoMoreData()
        }
        resultList.mj_footer?.isHidden = resultArr.count == 0
        resultList.reloadData()
    }
}
